const app = getApp();
const utils = require('../../utils/util.js');
var wxpay = require('../../utils/pay.js');
var setting = require('../../utils/settings.js');
var chat = require('../../utils/chat.js');
Page({
  data: {
    cardInfo: {},
    clientimgs: [],//浏览头像
    photoWall: [],//照片墙的照片
    swiperCurrent: 0,
    loadingMoreHidden: true,
    animationData: "",//底部弹出分享生成海报
    showModalStatus: false,
    animationData5: "",//名片点赞
    showModalStatus5: false,
    tagId: null,
    ishowLike: false,
    msgLength: 0,
    mobile: "",
    cardId: 0,//当前查看的名片id
    staffId: 0,//登陆者自己的主店
    showmsg: true, //是否查看自己的名片 false是自己
    showAi: false,//自己是否有创建玖玖客
    couponStatus: true, //是否显示优惠券
    videoObj: { vid: '',show: true},
    videosrc: "",
    productName: "",
    productPrice: "",
    pimages: "",
    productMsg: false, //是否显示分享商品弹出框
    currPid: 0, //分享的产品id
    saleUid: 0,//帮卖券的商家的uid
    seltoid: 0,//产品所属商家
    ShadowPrice: "",
    userInfo: {}, //操作者,店铺所有者
    myUserInfo: {}, //登陆者
    shareimgpath: '', // 分享小图临时路径
    payDialog: { isshow: false,ispay: false,title1: "",title2: "",submittext: "",isupdate: 1},  //代支付弹框
    branchDialog: {isshow: false,ispay: false,title1: "",title2: "",submittext: "",},  //创建分店弹窗
    couponListRed: [], //优惠券列表弹窗
    cardItemList: [], //消费卡列表
    isCouponCheck: 0, //是否属于核销员
    autoplays: true,
    interval: 5000,
    duration: 2000,
    showSignature: 0, //0收起商家介绍1展开商家介绍
    avaterList: [],//商家头图
    versionid: 1, //创建名片版本：0个人版，1共享推广版, 2商家版,3共享版，4智慧经营版, 5 云点单版
    source: 1,//1扫码2转发
    holderid: 0, //共享股东uid
    holderName: '',
    isPackage: 0,
    isAccredit: false, //是否授权
    isShowRightfloat: true, //右侧悬浮列表
    scrollTop: 0, //页面滑动
    showEmpover: false,
    liveList: [],
    startX: 0,
    aipage: 1,//1(收益、订单、客户、卡券、设置);2(直播、资源、AI销售、共享店铺、共享联盟)
    isCreateStaff: 0,
    proStaffid: 0,
    x: 370,
    y: 140,
    screenHeight: 500,
    navBarHeight: 44,
    navTitleText: '',//页面状态栏标题
    isPlatform: 0,//1平台跳转过来的
    loginCode: '',
    branchCount: 0,
    currentCity: '',
    isCreateBranch: 0,
    canIUseGetUserProfile: false,
    socketState: 'close', // open: 已连接, close: 已关闭
  },

  getBranchCount: function (uid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/staff/GetLastBranch?uid=' + uid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            that.setData({
              branchCount: res.data.Data.Id
            })
          }
        }
      }
    })
  },

  //创建分店弹窗
  createBranch: function () {
    let {
      branchDialog
    } = this.data;
    branchDialog.isshow = true;

    if (app.globalData.platform == 'ios') {
      branchDialog.ispay = false;
      branchDialog.title1 = "我要创建分店";
      branchDialog.submittext = "发送创建申请";
      if (this.data.versionid == 1) {
        branchDialog.submittext = "立即创建";
      }
    } else {
      branchDialog.ispay = true;
      branchDialog.title1 = "我要创建分店";
      branchDialog.submittext = "立即创建";
    }
    this.setData({
      branchDialog: branchDialog,
      versionid: 1
    })
  },
  // 立即创建
  toCreatBranchStore: function () {
    var that = this;
    let cardInfo = that.data.cardInfo.CardInfo;
    if (that.data.versionid == 3) {
      that.applyBranch(that.data.versionid);
    } else {
      if (app.globalData.platform != 'ios' || that.data.versionid == 1) {//安卓或苹果免费推广版
        wxpay.createStaffOrder(app, cardInfo.Id, that.data.versionid, 8);
        utils.aiCardActionRecord(24);
      } else {
        //发送创建申请
        that.applyBranch(that.data.versionid);
      }
    }
    let {
      branchDialog
    } = that.data;
    branchDialog.isshow = false;
    that.setData({
      branchDialog: branchDialog
    })
  },
  toApplyBranch: function () {
    this.applyBranch(this.data.versionid);
  },
  // 申请代付创建分店
  applyBranch: function (versionid) {
    let that = this;
    var cardInfo = that.data.cardInfo.CardInfo;
    wx.showLoading({title: '申请中',mask: true})
    wx.request({
      url: app.globalData.host + '/api/Staff/CreateStaffPayRequest?fromUid=' + app.globalData.userInfo.Uid + '&toUid=' + cardInfo.Uid + '&industryCode=' + versionid + '&isBranch=1',
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          utils.showToast('申请成功','success');
          that.dialogBranchState();
        } else {
          utils.showModal(res.data.Message);        
        }
      }
    })
  },

  // 切换分店
  searchBranch: function () {
    let that = this;
    let parentUid = that.data.cardInfo.CardInfo.ParentUid;
    if (parentUid == 0) {
      parentUid = that.data.cardInfo.CardInfo.Uid;
    }
    wx.navigateTo({
      url: '../branchStore/index?currentCity=' + that.data.currentCity + '&parentUid=' + parentUid,
    })
  },

  toCardList: function () {
    wx.redirectTo({
      url: '/pages/weijieke/cardList/index'
    })
  },

  getUserProfile: function () {
    let that = this;
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log('用于完善会员资料', res);
        utils.AuthorizeUserInfo(res, that.data.loginCode, function (flag) {
          wx.redirectTo({
            url: '/pages/weijieke/cardList/index'
          })
        });
      },
      fail: (err) => {
        utils.showToast('用户拒绝授权');
      }
    })
  },

  // 获取名片信息
  getAiCardInfo: function () {
    var that = this;
    var cardId = wx.getStorageSync("cardId");
    var videoObj = that.data.videoObj;
    let isFriendState = app.globalData.isFriendState;
    let uid = 0;
    if (isFriendState == 1) {
      uid = app.globalData.friendUid;
    } else {
      uid = app.globalData.userInfo.Uid;
    }
    if (!cardId) {
      cardId = that.data.cardId;
    }
    if (cardId) {
      wx.request({
        url: app.globalData.host + '/api/BusinessCard/GetAiCardDetail?uid=' + uid + '&staffId=' + cardId + '&shareUid=' + that.data.holderid,
        success: function (res) {
          that.setData({
            loadingMoreHidden: false
          })
          if (res.data.Code == 0) {
            var cardInfo = res.data.Data;
            let currentCity = that.data.currentCity;
            if (!currentCity) {
              if (cardInfo.CardInfo.Latitude == 0) {
                that.getLocation();
              } else {
                that.getCurrentCity(cardInfo.CardInfo.Latitude, cardInfo.CardInfo.Longitude);
              }
            }
            app.globalData.expireTime = cardInfo.CardInfo.ExpiredIn;
            let httpimg = 'https://static.711688.net.cn/upload/card/source/';
            let perSonAvater = utils.formatAvater(cardInfo.CardInfo.Avater, httpimg);
            videoObj.vid = cardInfo.CardInfo.VID;
            var imgs = cardInfo.CardInfo.Imgs;
            var avaters = cardInfo.Slides;
            var avaterList = [];
            var imgList = [];
            if (avaters) {//轮播头图
              avaters = avaters.split(',');
              for (let i = 0; i < avaters.length; i++) {
                var avaterObj = {
                  ShowImg: utils.formatAvater(avaters[i], httpimg)
                };
                avaterList.push(avaterObj);
              }
            } else {
              var avaterObj = {
                ShowImg: perSonAvater
              };
              avaterList.push(avaterObj);
            }
            that.setData({
              videoObj: videoObj,
              avaterList: avaterList,
              cardInfo: cardInfo
            })
            that.getBranchCount(cardInfo.CardInfo.Uid);
            // 浏览者头像
            var clientimgs = cardInfo.clientimgs;
            if (clientimgs) {
              if (clientimgs.length > 0 && clientimgs != null) {
                for (var k = 0; k < clientimgs.length; k++) {
                  clientimgs[k] = utils.formatAvater(clientimgs[k], 'https://static.711688.net.cn/upload/card/source/thumb600_600/');
                }
              }
            }
            if (imgs) {//照片墙
              imgs = imgs.split(",");
              for (let i = 0; i < imgs.length; i++) {
                imgList.push(utils.formatAvater(imgs[i], httpimg));
              }
              setTimeout(function () {
                that.setData({
                  photoWall: imgList,
                  clientimgs: clientimgs
                })
              }, 1000);
            }
            if (isFriendState != 1) {
              that.getIndexInfo(cardInfo);
              if (cardInfo.CardInfo.Uid == app.globalData.userInfo.Uid) {
                utils.getMsgUnRead(0, function (msgLength) {
                  that.setData({
                    msgLength: msgLength
                  })
                })
              } else {
                utils.getMsgUnRead(cardInfo.CardInfo.Uid, function (msgLength) {
                  that.setData({
                    msgLength: msgLength
                  })
                })
              }
              setTimeout(function () {
                that.toChat(app.globalData.userInfo.Uid);
              }, 10000);
              utils.aiCardActionRecord(4);
            }
            that.showMessege(cardInfo);
            that.getLiveList(cardInfo.CardInfo.Uid);
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.Message,
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: '/pages/weijieke/cardList/index',
                  })
                }
              }
            })
          }
        }
      })
    } else {
      that.setData({
        loadingMoreHidden: false
      })
      wx.redirectTo({
        url: '/pages/indexDefault/index',
      })
    }
  },
  
  getLocation: function () {
    let that = this;
    utils.getLocation((location)=>{
     that.getCurrentCity(location.lat, location.lng);
    },app);   
  },
  // 当前店铺城市
  getCurrentCity: function (lat, lng) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Tool/GetRegionByGeo?lat=' + lat + '&lng=' + lng,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.CityName) {
            that.setData({
              currentCity: res.data.Data.CityName
            })
          }
        }
      }
    })
  },

  // 平台首页
  toPlatfrom: function () {
    wx.reLaunch({
      url: '/pages/indexDefault/index',
    })
  },

  // 获取核销权限及优惠券弹窗、转发语
  getIndexInfo: function (cardInfo) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Staff/GetIndexInfo?type=10&staffId=' + cardInfo.CardInfo.Id + '&uid=' + app.globalData.userInfo.Uid + '&showShare=1',
      success: function (res) {
        var wxCouponTypeId = "";
        if (res.data.Code == 0) {
          let couponList = [];
          let cardItemList = [];
          //是否设置行业
          if (!res.data.Data.Industry || res.data.Data.Industry.Value == '') {
            if (app.globalData.userInfo.Uid == cardInfo.CardInfo.Uid && cardInfo.CardInfo.IndustryCode != 0) {
              wx.showModal({
                title: '提示',
                content: '请先设置行业',
                confirmText: '去设置',
                showCancel: false,
                success(res) {
                  wx.navigateTo({
                    url: '/pages/weijieke/industry/index',
                  })
                }
              })
            }
          }

          // 核销权限
          if (res.data.Data.CouponCheck.length > 0) {
            that.setData({
              isCouponCheck: 1
            })
          }
          // 股东礼包
          if (res.data.Data.IsPackage == 1) {
            that.getShareholderByUserid();
          }
          //转发语
          if (res.data.Data.ShareTip) {
            that.data.shareTitle = res.data.Data.ShareTip.Value;
          }
          //转发样式
          if (res.data.Data.ShareStyle) {
            var style = res.data.Data.ShareStyle.Value;
            if (style != 1) {
              that.data.shareimgpath = utils.formatAvater(style, 'https://static.711688.net.cn/upload/card/source/');
            } else {
              let avaters = cardInfo.Slides;
              if (avaters) {
                avaters = avaters.split(',');
                let showAvater = utils.formatAvater(avaters[0], 'https://static.711688.net.cn/upload/card/source/');
                that.data.shareimgpath = showAvater;
              } else {
                that.data.shareimgpath = utils.formatAvater(cardInfo.CardInfo.Avater, 'https://static.711688.net.cn/upload/card/source/');
              }
            }
          }
          //优惠券弹窗
          couponList = res.data.Data.CouponTypeList;
          if (couponList && couponList.length > 0) {
            for (let i = 0; i < couponList.length; i++) {
              if (couponList[i].WxCouponTypeId > 0) {
                wxCouponTypeId += couponList[i].WxCouponTypeId + ',';
              }
              couponList[i].usestarttime = couponList[i].usestarttime.substr(0, 10);
              couponList[i].useendtime = couponList[i].useendtime.substr(0, 10);
              couponList[i].showDetailPics = '';
              if (couponList[i].DetailPics) {
                var detailpics = couponList[i].DetailPics;
                var list = [];
                if (detailpics != '') {
                  var newDetailPics = detailpics.split(",");
                  for (let k = 0; k < newDetailPics.length; k++) {
                    list[k] = 'https://static.711688.net.cn/upload/coupondetail/' + newDetailPics[k];
                  }
                  couponList[i].showDetailPics = list[0];
                }
              }
            }
            if (wxCouponTypeId.length > 1) {
              wxCouponTypeId = wxCouponTypeId.substring(0, wxCouponTypeId.length - 1);
            }
            that.setData({
              couponListRed: couponList
            })
          }
          // 消费卡
          cardItemList = res.data.Data.CardItemList;
          if (cardItemList) {
            if (cardItemList.length > 0) {
              for (let i = 0; i < cardItemList.length; i++) {
                cardItemList[i].showDetailPics = '';
                if (cardItemList[i].DetailPics) {
                  var detailpics = cardItemList[i].DetailPics;
                  var list = [];
                  if (detailpics != '') {
                    var newDetailPics = detailpics.split(",");
                    for (let k = 0; k < newDetailPics.length; k++) {
                      list[k] = 'https://static.711688.net.cn/upload/coupondetail/' + newDetailPics[k];
                    }
                    cardItemList[i].showDetailPics = list[0];
                  }
                }
              }
            }
            that.setData({
              cardItemList: cardItemList
            })
          }
          that.setData({
            isPackage: res.data.Data.IsPackage
          })
        } else {
          utils.showModal(res.data.Message);    
        }
      }
    })
  },

  // 点击授权管理：
  toEmpover: function () {
    this.setData({
      showEmpover: !this.data.showEmpover
    })
  },

  // 老板是否授权所有操作给当前用户
  storeManager: function () {
    let that = this;
    let cardInfo = that.data.cardInfo;
    if (cardInfo) {
      wx.request({
        url: app.globalData.host + '/api/Staff/GetStaffExtendList?staffId=' + cardInfo.CardInfo.Id + '&keyword=25',
        success: function (res) {
          if (res.data.Code == 0) {
            let authorizeList = res.data.Data;
            if (authorizeList.length > 0) {
              let hasAuthorize = false;
              for (let i = 0; i < authorizeList.length; i++) {
                if (app.globalData.myUserInfo.Uid == authorizeList[i].Value) {
                  app.globalData.userInfo.Uid = cardInfo.CardInfo.Uid;
                  hasAuthorize = true;
                  that.setData({
                    userInfo: app.globalData.userInfo,
                    myUserInfo: app.globalData.myUserInfo,
                    showAi: true
                  })
                  wx.showToast({
                    title: '授权成功',
                    mask: true,
                    duration: 1500
                  })
                  that.onShow();
                  break;
                }
              }
              if (!hasAuthorize) {
                utils.showToast('商家未授权');               
              }
            } else {
              utils.showToast('商家未授权');
            }
          }
        }
      })
    }
  },
  // 退出管理
  exitStoreManager: function () {
    let that = this;
    app.globalData.userInfo.Uid = app.globalData.myUserInfo.Uid;
    that.setData({
      userInfo: app.globalData.userInfo,
      showAi: false
    })
    utils.showToast('退出成功');
    that.onShow();
  },

  //查看我的名片
  lookMyCardInfo: function () {
    var staffid = wx.getStorageSync("staffid");
    wx.reLaunch({
      url: '/pages/index/index?id=' + staffid + '&source=2',
    })
  },

  // 查看最近访问的名片列表
  formSubmitCardList: function (e) {
    let that = this;
    let isAccredit = that.data.isAccredit;
    if (e.detail.iv) {
      if (!isAccredit) {//弹出授权框且同意
        utils.AuthorizeUserInfoOld(e, that.data.loginCode, function (flag) {
          if (flag) {
            wx.redirectTo({
              url: '/pages/weijieke/cardList/index'
            })
          } else {//注册失败，重新点击授权
            wx.login({
              success: function (res) {
                that.data.loginCode = res.code;
              }
            })
          }
        });
      } else {
        wx.redirectTo({
          url: '/pages/weijieke/cardList/index'
        })
      }
    }
  },

  //转发
  formSubmitCardShare: function () {
    this.showModal();
  },

  // 消息通知
  toMsgNotify: function () {
    wx.navigateTo({
      url: '/pages/msgNotify/index',
    })
  },

  // 导出经营报表
  toReports: function () {
    wx.navigateTo({
      url: '/merchant/merchants/businReports/index?childUid=' + app.globalData.userInfo.Uid + '&parentuid=' + app.globalData.userInfo.Uid + '&isAll=0',
    })
  },

  // 进入页面参数处理
  onLoad: function (e) {
    console.log('首页参数', e);
    let that = this;
    that.getOnloadParam(e); //加载参数
    if (wx.getUserProfile) {
      that.setData({
        canIUseGetUserProfile: true
      })
    }
    var info = wx.getSystemInfoSync();
    var screenHeight = info.screenHeight - 150;
    let screenWidth = info.screenWidth;
    that.setData({
      screenHeight: screenHeight,
      x: screenWidth,
      navBarHeight: app.globalData.navBarHeight
    })
    wx.login({
      success: (res) => {
        that.data.loginCode = res.code;
      },
    })
    that.bindClient();
    let cardId = wx.getStorageSync('cardId');
    that.data.cardId = cardId;
    that.setData({
      couponStatus: setting.get_user_coupon_dialog_status(cardId)  //当前查看的名片
    })
  },

  getOnloadParam: function (e) {
    if (!e){ return; } 
    let params = decodeURIComponent(e.scene);
    if (params && params != 'undefined') {//扫描小程序二维码进入
      let plist = '';
      let type = 0;
      if (params.indexOf('p-') != -1) {
        type = params.match(/t-(\S*)\*p/)[1];//路由
        let param = params.match(/p-(\S*)/)[1];//参数
        plist = param.split('_');
      } else {
        type = params.match(/t=(\S*)&p/)[1];//路由
        let param = params.match(/p=(\S*)/)[1];//参数
        plist = param.toString().split('#');
      }
      if (type == 1) {//推荐二维码
        if (plist[0]) {
          this.data.cardId = plist[0];
          wx.setStorageSync("cardId", plist[0]);
        }
        if (plist[1]) {
          this.data.isCreateStaff = 2;//推荐二维码跳过来的，未创建名片直接弹窗版本选择弹窗
        }
      } else if (type == 2) {//商品海报二维码
        if (plist[0]) {
          this.data.cardId = plist[0];
          wx.setStorageSync("cardId", plist[0]);
        }
        if (plist[1]) {
          this.data.currPid = plist[1];
          this.getProductInfo(plist[1]);
          if (plist[2]) {
            this.data.saleUid = plist[2];
          }
          if (plist[3]) {
            this.data.proStaffid = plist[3];
          }
        }
      } else if (type == 3) {//股东礼包
        this.data.holderid = plist[1];
        wx.setStorageSync("cardId", plist[0]);
        this.getWxUserInfo(plist[1]);
        this.data.source = 4;
      } else if (type == 10) {
        this.data.cardId = plist[0];
        wx.setStorageSync("cardId", plist[0]);
        this.data.source = 1;
      }
    } else {
      console.log('名片首页cardid',e.id);
      if (e.id) {
        this.data.cardId = e.id;
        wx.setStorageSync("cardId", e.id);
      }
      if (e.isCreateBranch) {
        this.data.isCreateBranch = e.isCreateBranch;
        this.createBranch();
      }
      if (e.currentCity) {
        this.data.currentCity = e.currentCity;
      }
      if (e.isPlatform) {
        this.setData({
          isPlatform: e.isPlatform
        })
      }
      if (e.isCreateStaff) {//推荐二维码跳过来的，未创建名片直接弹窗版本选择弹窗
        this.data.isCreateStaff = e.isCreateStaff;
      }
      if (e.proStaffid) {
        this.data.proStaffid = e.proStaffid;
      }
      if (e.pid) {
        this.data.currPid = e.pid;
        this.getProductInfo(e.pid);
        if (e.saleUid) {
          this.data.saleUid = e.saleUid;
        }
        if (e.seltoid) {
          this.data.seltoid = e.seltoid;
        }   
      }
      if (e.holderid) {
        this.data.holderid = e.holderid;
        this.setData({
          holderName: e.holderName
        })
      }
      if (e.shareUid) {
        this.data.holderid = e.shareUid;
      }
      if (e.source) {
        this.data.source = e.source;
      }
      console.log('领卡参数',e.revUid)
      if(e.revUid){
        this.receiveJJK(e.revUid);  //带此参数,自动领玖玖卡 2022-04-11
      }
    }
  },
  getWxUserInfo: function (uid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/User/GetPartUser?uid=' + uid,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            holderName: res.data.Data.NickName
          })
        }
      },
    })
  },

  // 登陆者是否有玖玖客
  getStaffByUid: function (userid) {
    let that = this;
    let showAi = false;
    let staffId = 0;
    wx.request({
      url: app.globalData.host + '/api/Staff/GetStaffIdByUid?Uid=' + userid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            showAi = true;
            staffId = res.data.Data.Id;
            wx.setStorageSync("staffid", res.data.Data.Id)
          } else {
            wx.removeStorageSync("staffid");
            that.setData({
              couponStatus: false
            })
            that.toCreatMyCardInfo();
          }
          that.setData({
            showAi: showAi,
            staffId: staffId
          })
        }
      },
    })
  },

  //离开当前页面
  onUnload: function () {
    if(this.data.socketState =='open'){
      utils.toCloseSocket();
    }    
  },
  onHide: function () {
    if(this.data.socketState =='open'){
      utils.toCloseSocket();
    }   
  },

  // 关于首页商品弹窗
  closeMsg: function () {
    this.setData({
      productMsg: false
    })
  },
  //跳转商品详情页
  lookProduct: function () {
    var that = this;
    let seltoid = that.data.seltoid;
    var cardInfo = that.data.cardInfo.CardInfo;
    if (!seltoid) {
      seltoid = cardInfo.Uid;
    }
    wx.navigateTo({
      url: '/pages/productDetails/index?pid=' + that.data.currPid + "&seltoid=" + seltoid + "&name=" + cardInfo.Name + '&saleUid=' + that.data.saleUid + '&proStaffid=' + that.data.proStaffid,
      complete: function () {
        that.setData({productMsg: false})
      }
    })
  },
  //获取商品信息
  getProductInfo: function (pid) {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Store/Product?pid=' + pid,
      success: function (res) {
        if (res.data.Code == 0) {
          var p = res.data.Data;
          let pimages = utils.formatAvater(p.ProductImageList[0].ShowImg, 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/editor/');
          if (p.ProductImageList[0].ShowImg.indexOf('ps') != -1) {
            pimages = utils.formatAvaterByProHead(p.ProductImageList[0].ShowImg);
          }
          that.data.seltoid = p.ProductInfo.AddUid;
          that.setData({
            productMsg: true,
            productName: p.ProductInfo.Name,
            productPrice: p.ProductInfo.ShopPrice,
            pimages: pimages,
            ShadowPrice: p.ProductInfo.ShadowPrice
          })
        } else {
          utils.showModal(res.data.Message);          
        }
      },
    })
  },

  // 编辑首页信息后重新获取信息
  getInfo: function (cardId) {
    let that = this;
    var videoObj = that.data.videoObj;
    let httpimg = 'https://static.711688.net.cn/upload/card/source/';
    wx.request({
      url: app.globalData.host + '/api/Staff/GetInfo?id=' + cardId,
      success: function (res) {
        if (res.data.Code == 0) {
          videoObj.vid = res.data.Data.VID;
          let perSonAvater = utils.formatAvater(res.data.Data.Avater, httpimg);
          var avaters = res.data.Data.Slides;
          var imgs = res.data.Data.Imgs;
          var avaterList = [];
          var imgList = [];
          if (avaters) {//轮播头图
            avaters = avaters.split(',');
            for (let i = 0; i < avaters.length; i++) {
              var avaterObj = {
                ShowImg: utils.formatAvater(avaters[i], httpimg)
              };
              avaterList.push(avaterObj);
            }
          } else {
            avaterList.push(perSonAvater);
          }
          if (imgs) {//照片墙
            imgs = imgs.split(",");
            for (let i = 0; i < imgs.length; i++) {
              imgList.push(utils.formatAvater(imgs[i], httpimg));
            }
          }
          that.setData({
            videoObj: videoObj,
            avaterList: avaterList,
            photoWall: imgList
          })
        }
      },
    })
  },

  //进入聊天页面
  formSubmit: function () {
    let that = this;
    let nickname = that.data.cardInfo.CardInfo.Name;
    wx.request({
      url: app.globalData.host + '/api/IM/UserByOpenId?openId=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0 && res.data.Data) {
          let fromuid = res.data.Data.Id;
          wx.request({
            url: app.globalData.host + '/api/IM/UserByOpenId?openId=' + that.data.cardInfo.CardInfo.Uid,
            success: function (res2) {
              if (res2.data.Code == 0 && res2.data.Data) {
                let touid = res2.data.Data.Id;
                let chatparam = 'touid=' + touid + '&fromuid=' + fromuid + '&nickname=' + nickname + '&storeid=' + app.globalData.storeId
                wx.navigateTo({
                  url: '/pages/h5page/index?url=sessionDetail.html&chatparam=' + encodeURIComponent(chatparam),
                })
              }
            }
          })
        }
      }
    })
    utils.aiCardActionRecord(18);
  },

  // 扫一扫
  formScan: function () {
    wx.scanCode({
      success(res) {
        if (res.path) {
          let url = res.path;
          if (url.substr(0, 1) != '/') {
            url = "/" + url
          }
          setTimeout(function () {
            wx.navigateTo({
              url: url,
            })
          }, 1000)
        }

      }
    })
  },

  //获取手机号
  getPhoneNumber: function (e) {
    utils.getMobile(e);
  },

  //复制文本
  copyDataInfo: function (e) {
    let data = e.currentTarget.dataset.copy;
    let wxid = e.currentTarget.dataset.wxid;
    wx.setClipboardData({
      data: data,
      success: function (res) {
        if (wxid == 1) { //复制微信
          utils.aiCardActionRecord(3);
        }
        if (wxid == 2) { //邮箱
          utils.aiCardActionRecord(12);
        }
      }
    })
  },

  //拨打电话
  makeCallPhone: function (e) {
    let mobile = e.currentTarget.dataset.mobile;
    if (mobile) {
      wx.makePhoneCall({
        phoneNumber: mobile
      })
    }
  },

  // 生成海报
  toPoste: function (e) {
    var cardInfo = JSON.stringify(this.data.cardInfo)
    var showmode = e.currentTarget.dataset.showmode;
    wx.navigateTo({
      url: '/pages/weijieke/sharePoste/index?cardinfo=' + this.encodeUnicode(cardInfo) + '&showmode=' + showmode + '&stylemer=9',
    })
  },

  // 转为unicode 编码
  encodeUnicode: function (str) {
    var res = [];
    for (var i = 0; i < str.length; i++) {
      res[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4);
    }
    return "\\u" + res.join("\\u");
  },

  //图片预览
  prewCardImg: function (e) {
    let imgList = this.data.photoWall;
    let src = e.currentTarget.dataset.currsrc;
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: imgList // 需要预览的图片http链接列表
    })
  },

  // 底部弹出层
  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },

  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },

  // 名片点赞
  showAddCardUp: function (e) {
    let cardId = e.currentTarget.dataset.cardid;
    if (cardId != null) {
      var animation = wx.createAnimation({
        duration: 1000,
        timingFunction: "linear",
        delay: 0
      })
      this.animation = animation;
      animation.scale(1, 1).translateY(0).step();
      this.setData({
        animationData5: animation.export(),
        showModalStatus5: true,
        ishowLike: true
      })
      setTimeout(function () {
        animation.scale(2, 2).translateY(-30).step();
        this.setData({
          animationData5: animation.export(),
        })
      }.bind(this), 200)
      var that = this;
      setTimeout(function () {
        that.setData({
          showModalStatus5: false,
          ishowLike: true
        })
        that.addCardUp(cardId)
      }, 1000)
    }
  },
  
  //名片点赞
  addCardUp: function (cardid) {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/BusinessCard/AddCardUp?uid=' + app.globalData.userInfo.Uid + '&staffId=' + cardid,
      success: function (res) {
        if (res.data.Code == 0) {
          that.getAiCardInfo();
        } else {
          utils.showModal(res.data.Message);
        }
      },
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.hideModal();
    let isFriendState = app.globalData.isFriendState;
    if (isFriendState == 1) {//朋友圈分享
      that.getAiCardInfo();
      that.getStaffIdByUid();
      return;
    }
    if (app.globalData.userInfo) {
      var mobile = app.globalData.userInfo.Mobile;
      utils.isAccredit(function (isAccredit) {
        that.setData({isAccredit: isAccredit})
      });
      that.getAiCardInfo();

      that.setData({
        mobile: mobile,
        userInfo: app.globalData.userInfo,
        myUserInfo: app.globalData.myUserInfo
      })
      if (that.data.isCreateStaff == 2) {
        that.getStaffByUid(app.globalData.userInfo.Uid);
      } else {
        that.getStaffIdByUid();
      }
    } else {
      setTimeout(function () {
        this.onShow();
      }.bind(that), 1000)
    }
  },

  // 连接socket监听聊天消息
  toChat: function (uid) {
    let that = this;
    chat.initChat(uid, function(){
      that.data.socketState = 'open'; //连接成功
     },
     function(){
        that.setData({msgLength: 1}); //新消息
    });
   },
  
   showMessege: function (cardInfo) {
    var showmsg = true;
    let versionid = 1;
    let isFriendState = app.globalData.isFriendState;
    let userInfo = app.globalData.userInfo;
    let myUserInfo = app.globalData.myUserInfo;
    if (isFriendState == 1) {
      showmsg = true;
    } else {
      if (userInfo.Uid == cardInfo.CardInfo.Uid || myUserInfo.Uid == cardInfo.CardInfo.ParentUid || myUserInfo.Uid == cardInfo.CardInfo.Uid) {
        showmsg = false;//自己
        versionid = cardInfo.CardInfo.IndustryCode;
        userInfo.Uid = cardInfo.CardInfo.Uid;
        app.globalData.userInfo = userInfo;
      } else {
        showmsg = true;
      }
    }
    if (this.data.isCreateBranch == 1) {
      versionid = 1;
    }
    this.setData({
      showmsg: showmsg,
      versionid: versionid,
      userInfo: userInfo
    })
  },

  // 展开商家介绍
  showSignature: function (e) {
    let showSignature = e.currentTarget.dataset.showsignature;
    this.setData({
      showSignature: showSignature
    })
  },

  //判断是否创建过名片
  getStaffIdByUid: function () {
    var that = this;
    let uid = app.globalData.userInfo.Uid;
    if (app.globalData.isFriendState == 1) {
      uid = app.globalData.friendUid;
    }   
    console.log('uid',uid)
    wx.request({
      url: app.globalData.host + '/api/Staff/GetStaffIdByUid?Uid=' + uid,
      success: function (res) {
        if(res.data.Code != 0){
          utils.showModal(res.data.Message);     
          return;
        }
        if(! res.data.Data){
          wx.removeStorageSync("staffid");
          that.getJJKInfo();
        }else{
          wx.setStorageSync("staffid", res.data.Data.Id)
          that.setData({
            showAi: true,
            staffId: res.data.Data.Id
          })
        }
      },
    })
  },

  //编辑个人资料
  ediorMobile(e) {
    let cardId = e.currentTarget.dataset.cardid;
    wx.navigateTo({
      url: '/pages/weijieke/editorCard/index?staffid=' + cardId,
    })
  },

  //编辑我的介绍
  editorMyTro() {
    wx.navigateTo({
      url: '/pages/h5page/index?url=mysign.html',
    })
  },

  //编辑我的照片
  editorMyPhoto() {
    var cardId = wx.getStorageSync("cardId")
    wx.navigateTo({
      url: '/pages/weijieke/myPhoto/index?staffid=' + cardId + '&location=1',
    })
  },

  //顶部按钮导航
  onAiTabbarItemTap: function (ev) {
    let that = this;    
    that.checkExpiredIn(function (expired) {
      if (expired) {
        that.showModalTips();
      } else {
        let url = ev.detail.target.dataset.page;
        let key = ev.detail.target.dataset.key;   //按钮索引      
        let industryCode = that.data.cardInfo.CardInfo.IndustryCode;

        if (key == 3 && industryCode < 2) {   //卡券
          that.updateAicard(4);
          return;
        }
        if (key == 5 && industryCode < 3) {   //直播
          that.updateAicard(4);
          return;
        } 
        if (key == 8 && industryCode != 3) {  //共享店铺
          that.updateAicard(3);
          return;
        }
        if (url == "chatMessageList.html"){   //即时聊天
          that.toChatPage();
          return;
        }        
        if(url.indexOf('.html') > -1){
          url = '/pages/h5page/index?url=' + url;
        }
        wx.navigateTo({url: url})
      }
    })
  },
  //即时聊天页面
  toChatPage: function(){
    wx.request({
      url: app.globalData.host + '/api/IM/UserByOpenId?openId=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0 && res.data.Data) {
          let fromuid = res.data.Data.Id;
          let chatparam = 'uid=' + fromuid + '&storeid=' + app.globalData.storeId
          wx.navigateTo({
            url: '/pages/h5page/index?url=chatMessageList.html&chatparam=' + encodeURIComponent(chatparam),
          })
        }
      }
    })
  },
  // 获取用户所属股东
  getShareholderByUserid: function () {
    let that = this;
    let cardId = wx.getStorageSync("cardId");
    wx.request({
      url: app.globalData.host + '/api/Shareholder/GetShareholderByClient?staffId=' + cardId + '&uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.info) {
            that.setData({
              holderName: res.data.Data.info.Name
            })
          }
        } else {
          utils.showModal(res.data.Message);
        }
      }
    })
  },

  // 一键领取优惠券
  getCoupons: function () {
    wx.showLoading({
      title: '正在领取',
      mask: true
    })
    let that = this;
    let cardId = wx.getStorageSync('cardId');
    var couponTypeIds = "";
    let couponListRed = that.data.couponListRed;

    for (var i = 0; i < couponListRed.length; i++) {
      couponTypeIds += couponListRed[i].coupontypeid + ",";
    }
    couponTypeIds = couponTypeIds.substr(0, couponTypeIds.length - 1);
    wx.request({
      url: app.globalData.host + '/api/Coupon/BatchReceiveCoupon',
      data: {
        uid: app.globalData.userInfo.Uid,
        couponTypeIds: couponTypeIds,
      },
      method: 'POST',
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          wx.showToast({
            title: '领取成功',
            duration: 1000
          })
          setting.set_user_coupon_dialog_status(cardId, false);
          wx.reLaunch({
            url: '/merchant/merchants/myCardCoupon/index',
          })
          that.setData({
            couponStatus: false
          })
        } else {
          utils.showModal(res.data.Message);         
        }
      }
    })
  },
  // 一键领取优惠券(共享版)
  getCouponsHolder: function () {
    let that = this;
    let cardId = wx.getStorageSync('cardId');
    let isPackage = that.data.isPackage;
    var couponTypeIds = "";
    let couponListRed = that.data.couponListRed;
    if (isPackage == 0) {
      for (var i = 0; i < couponListRed.length; i++) {
        couponTypeIds += couponListRed[i].coupontypeid + ",";
      }
      couponTypeIds = couponTypeIds.substr(0, couponTypeIds.length - 1);
    } else {
      couponTypeIds = '';
    }
    let isAccredit = that.data.isAccredit;
    if (!isAccredit) {
      let back = '/pages/index/index';
      wx.navigateTo({
        url: '../accredit/index?back=' + back + '&createUid=' + that.data.cardInfo.CardInfo.Uid + '&couponTypeIds=' + couponTypeIds
      })
    } else {
      wx.showLoading({title: '正在领取',mask: true})
      wx.request({
        url: app.globalData.host + '/api/Coupon/AddUserPackage',
        data: {
          uid: app.globalData.userInfo.Uid,
          createUid: that.data.cardInfo.CardInfo.Uid,
          staffId: cardId,
          couponTypeIds: couponTypeIds,
        },
        method: 'POST',
        success: function (res) {
          wx.hideLoading();
          if (res.data.Code == 0) {
            wx.showToast({
              title: '领取成功',
              duration: 1000
            })
            setting.set_user_coupon_dialog_status(cardId, false);
            wx.reLaunch({
              url: '/merchant/merchants/myCardCoupon/index',
            })
            that.setData({
              couponStatus: false
            })
          } else {
            utils.showModal(res.data.Message);
          }
        }
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    var that = this;    
    let cardInfo = that.data.cardInfo;    
    let shareTitle = "你好，我是" + cardInfo.CardInfo.Company + "的" + cardInfo.CardInfo.Name;
    if (that.data.shareTitle) {
      shareTitle = that.data.shareTitle;
    } 
    let path = '/pages/index/index?id=' + cardInfo.CardInfo.Id + '&source=2&revUid=' +  app.globalData.userInfo.Uid;
    if(that.data.cardUser && that.data.cardUser.saleUid > 0){
      path =  '/pages/index/index?id=' + cardInfo.CardInfo.Id + '&source=2&revUid=' +  + that.data.cardUser.saleUid;
    }
    console.log(path)
    utils.aiCardActionRecord(2);
    return {
      imageUrl: that.data.shareimgpath,
      title: shareTitle,
      path: path,
      success: function (res) {
        utils.showModal('分享成功');     
        that.hideModal();
      }
    }
  },

  //分享朋友圈
  onShareTimeline: function () {
    let that = this;
    var cardInfo = that.data.cardInfo;
    var shareTitle = cardInfo.CardInfo.Company;
    if (that.data.shareTitle) {
      shareTitle = that.data.shareTitle;
    } 
    let imageUrl = '';
    if (cardInfo.CardInfo.IndustryCode > 0) {
      let avaters = cardInfo.Slides;
      avaters = avaters.split(',');
      imageUrl = utils.formatAvater(avaters[0], 'https://static.711688.net.cn/upload/card/source/');
    } else {
      imageUrl = utils.formatAvater(cardInfo.CardInfo.Avater, 'https://static.711688.net.cn/upload/card/source/');
    }  
    var path = 'id=' + cardInfo.CardInfo.Id + '&uid=' + app.globalData.userInfo.Uid +'&revUid=' + app.globalData.userInfo.Uid + '&isFriendState=1';
    if(that.data.cardUser && that.data.cardUser.saleUid > 0){
        path = 'id=' + cardInfo.CardInfo.Id + '&uid=' + app.globalData.userInfo.Uid +'&revUid=' +  that.data.cardUser.saleUid+ '&isFriendState=1';
    }
    console.log(path);
    return {
      title: shareTitle,
      query: path,
      imageUrl: imageUrl
    }
  },

  tapChatFrom: function () {
    if (this.data.cardInfo.CardInfo) {
      utils.tapChatFrom(this.data.cardInfo.CardInfo);
    }
  },

  //监听用户滑动页面事件
  onPageScroll: function (e) {
    this.data.scrollTop = e.scrollTop;
    this.setData({
      isShowRightfloat: false
    })
    let timer = setTimeout(() => {
      if (this.data.scrollTop === e.scrollTop) {
        this.data.scrollTop = e.scrollTop;
        this.setData({
          isShowRightfloat: true
        })
        clearTimeout(timer);
      }
    }, 3000);
  },

  //地图导航
  openMapLocation: function () {
    var that = this;
    var cardInfo = that.data.cardInfo;
    wx.showModal({
      title: '提示',
      content: '是否打开地图导航',
      success: function (res) {
        if (res.confirm) {
          wx.getLocation({
            type: 'gcj02',
            success: function (res) {
              wx.openLocation({
                latitude: cardInfo.CardInfo.Latitude,
                longitude: cardInfo.CardInfo.Longitude,
                scale: 28,
                name: "点击右边打开地图导航",
                address: cardInfo.CardInfo.Address
              })
            }
          })
        }
      }
    })
  },

  // 优惠券详情
  toCouponDetail: function (e) {
    let type = e.currentTarget.dataset.type;
    let couponid = e.currentTarget.dataset.couponid;
    let coupontypeid = e.currentTarget.dataset.coupontypeid;//股东礼包查看详情需要
    wx.navigateTo({
      url: '/merchant/merchants/cardDetails/index?type=' + type + '&couponid=' + couponid + '&coupontypeid=' + coupontypeid,
    })
  },

  // 消费卡详情
  toCardItemDetail: function (e) {
    let id = e.currentTarget.dataset.id;
    let type = e.currentTarget.dataset.type;
    let cid = e.currentTarget.dataset.cid;
    wx.navigateTo({
      url: '/merchant/merchants/cardDetails/index?type=' + type + '&cid=' + cid + '&ids=' + id,
    })
  },

  // 悬浮右侧菜单显示控制
  changeRightFloat: function () {
    this.setData({
      isShowRightfloat: !this.data.isShowRightfloat
    })
  },

  touchS: function (e) {
    if (e.touches.length == 1) {
      this.data.startX = e.touches[0].clientX;
    }
  },
  touchE: function (e) {
    var that = this;
    if (e.changedTouches.length == 1) {
      var endX = e.changedTouches[0].clientX;
      var disX = that.data.startX - endX;
      let aipage = that.data.aipage;
      if (disX >= 1) {
        aipage = 2;
      } else if (disX < -1) {
        aipage = 1;
      }
      that.setData({
        aipage: aipage
      })
    }
  },

  // 关于玖玖客注册、申请代付
  // 注册玖玖客授权手机号
  getMobiles: function (e) {
    let that = this;
    utils.getMobile(e, function (mobiles) {
      if (mobiles) {
        that.toCreatMyCardInfo();
      } else {
        utils.showToast('请授权手机号');     
      }
    })
  },
  //创建我的名片
  toCreatMyCardInfo: function () {
    let {
      payDialog
    } = this.data;
    payDialog.isshow = true;

    if (app.globalData.platform == 'ios') {
      payDialog.ispay = false;
      payDialog.title1 = "您还不是会员";
      payDialog.submittext = "发送创建申请";
      if (this.data.versionid == 1) {
        payDialog.submittext = "立即创建";
      }
      if (this.data.showAi) {
        payDialog.title1 = "您的玖玖客已到期";
        payDialog.submittext = "发送续费申请"
      }
    } else {
      payDialog.ispay = true;
      payDialog.title1 = "您还不是会员";
      payDialog.submittext = "立即创建";
      if (this.data.showAi) {
        payDialog.title1 = "您的玖玖客已到期";
        payDialog.submittext = "立即续费";
      }
    }
    this.setData({
      payDialog: payDialog
    })
  },
  // 创建名片时1选择共享推广版4智慧经营版
  versionSelect: function (e) {
    let versionid = e.currentTarget.dataset.versonid;
    let payDialog = this.data.payDialog;
    let branchDialog = this.data.branchDialog;
    if (versionid == 1) {
      payDialog.submittext = '立即创建';
      branchDialog.submittext = '立即创建';
    }
    if (versionid == 4) {
      if (app.globalData.platform == 'ios') {
        payDialog.submittext = "发送创建申请";
        branchDialog.submittext = '发送创建申请';
        if (this.data.showAi) {
          payDialog.submittext = "发送续费申请"
        }
      } else {
        payDialog.submittext = "立即创建";
        branchDialog.submittext = '立即创建';
        if (this.data.showAi) {
          payDialog.submittext = "立即续费";
        }
      }
    }
    this.setData({
      versionid: versionid,
      payDialog: payDialog,
      branchDialog: branchDialog
    })
  },
  //创建支付安卓手机,苹果手机发送申请(先授权微信头像昵称)
  creatMyCardPay: function (e) {
    let that = this;
    let isAccredit = that.data.isAccredit;
    if (e.detail.iv) {
      if (!isAccredit) {//弹出授权框且同意
        utils.AuthorizeUserInfoOld(e, that.data.loginCode, function (flag) {
          if (flag) {
            that.toCreatMyCardPay();
          } else {//注册失败，重新点击授权
            wx.login({
              success: function (res) {
                that.data.loginCode = res.code;
              }
            })
          }
        })
      } else {
        that.toCreatMyCardPay();
      }
    } else {
      utils.showToast('请授权微信头像、昵称');   
    }
  },
  //创建支付安卓手机,苹果手机发送申请(先授权微信头像昵称)===用户授权api修改
  creatMyCardPayByfile: function () {
    let that = this;
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        utils.AuthorizeUserInfo(res, '', function (flag) {
          if (flag) {
            that.toCreatMyCardPay();
          }
        });
      },
      fail: (err) => {
        utils.showToast('请授权微信头像、昵称');
      }
    })
  },
  //创建支付安卓手机,苹果手机发送申请
  toCreatMyCardPay: function (e) {
    var that = this;
    let cardInfo = that.data.cardInfo.CardInfo;
    if (that.data.versionid == 3) {
      that.createStaffPayRequest(that.data.versionid);
    } else {
      if (app.globalData.platform != 'ios' || that.data.versionid == 1) {//安卓或苹果免费推广版
        wxpay.createStaffOrder(app, cardInfo.Id, that.data.versionid);
        utils.aiCardActionRecord(24);
      } else {
        //发送创建申请
        that.createStaffPayRequest(that.data.versionid);
      }
    }
    let {
      payDialog
    } = that.data;
    payDialog.isshow = false;
    that.setData({
      payDialog: payDialog
    })
  },
  //申请代付
  applyCardPay: function (e) {
    var that = this;
    let isAccredit = that.data.isAccredit;
    if (e.detail.iv) {
      if (!isAccredit) {//弹出授权框且同意
        // utils.AuthorizeUserInfo(e, that.data.loginCode);
        utils.AuthorizeUserInfoOld(e, that.data.loginCode, function (flag) {
          if (flag) {
            that.createStaffPayRequest(that.data.versionid);
          } else {//注册失败，重新点击授权
            wx.login({
              success: function (res) {
                that.data.loginCode = res.code;
              }
            })
          }
        })
      } else {
        that.createStaffPayRequest(that.data.versionid);
      }
    } else {
      utils.showToast('请授权微信头像、昵称');
    }
  },
  //申请代付===用户授权api修改
  applyCardPayByfile: function () {
    var that = this;
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log('用于完善会员资料', res);
        utils.AuthorizeUserInfo(res, '', function (flag) {
          if (flag) {
            that.createStaffPayRequest(that.data.versionid);
          }
        });
      },
      fail: (err) => {
        utils.showToast('请授权微信头像、昵称');
      }
    })
  },
  //申请代付
  createStaffPayRequest: function (versionid) {
    let that = this;
    var cardInfo = that.data.cardInfo.CardInfo;
    wx.showLoading({title: '申请中',mask: true})
    wx.request({
      url: app.globalData.host + '/api/Staff/CreateStaffPayRequest?fromUid=' + app.globalData.userInfo.Uid + '&toUid=' + cardInfo.Uid + '&industryCode=' + versionid,
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          that.dialogsState();
          utils.showToast('申请成功');         
        } else {
          utils.showModal(res.data.Message);          
        }
      }
    })
  },
  // 升级弹窗
  updateAicard: function (isupdate) {
    let {
      payDialog
    } = this.data;
    payDialog.isshow = true;
    payDialog.isupdate = isupdate;
    if (app.globalData.platform == 'ios' || isupdate == 3) {
      payDialog.ispay = false;
      payDialog.title1 = "升级后才能使用该功能";
      payDialog.submittext = "发送升级申请";
    } else {
      payDialog.ispay = true,
        payDialog.title1 = "升级后才能使用该功能";
      payDialog.submittext = "立即升级";
    }
    this.setData({
      payDialog: payDialog
    })
  },
  //判断是否过期
  checkExpiredIn: function (Callback) {
    var ExpiredIn = app.globalData.expireTime;
    var year = ExpiredIn.substr(0, 4);
    var month = ExpiredIn.substr(5, 2);
    var day = ExpiredIn.substr(8, 2);
    var times = ExpiredIn.substr(11, 8);
    ExpiredIn = year + "/" + month + "/" + day + "\t" + times;
    if (new Date(ExpiredIn) < new Date(utils.getCurrentTodayDate())) { //已过期
      Callback(true);
    } else {
      Callback(false);
    }
  },
  //付费提醒
  showModalTips: function () {
    var that = this;
    wx.showModal({
      title: '您的使用已到期',
      content: '玖玖客版本已过期,是否需要续费继续使用？',
      success: function (res) {
        if (res.confirm) {
          that.toCreatMyCardInfo();
        } else {
          wx.navigateBack({
            delta: 1,
          })
        }
      },
      fail: function (err) {
        wx.navigateBack({
          delta: 1,
        })
      }
    })
  },
  //关闭注册玖玖客弹框
  dialogsState: function () {
    let {
      payDialog
    } = this.data;
    if (payDialog.isshow) {
      payDialog.isshow = false;
    } else {
      payDialog.isshow = true;
    }
    this.setData({
      payDialog: payDialog
    })
  },
  dialogBranchState: function () {
    let {
      branchDialog
    } = this.data;
    if (branchDialog.isshow) {
      branchDialog.isshow = false;
    } else {
      branchDialog.isshow = true;
    }
    this.setData({
      branchDialog: branchDialog
    })
  },

  // 关闭红包弹窗
  closedialog: function (e) {
    let cardId = e.currentTarget.dataset.cardid
    setting.set_user_coupon_dialog_status(cardId, false);
    this.setData({
      couponStatus: false
    })
  },

  //直播
  getLiveList: function (createUid) {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/weapp/GetLiveListByUser?uid=' + createUid + '&storeId=' + app.globalData.storeId,
      success: function (res) {
        if (res.data.Code == 0) {
          let liveList = res.data.Data.Items;
          let showList = [];
          if (liveList && liveList.length > 0) {
            //101 直播中102 未开始103 已结束104 禁播105 暂停中106 异常107 已过期
            for (let i = 0; i < liveList.length; i++) {
              liveList[i].CoverImg = utils.formatAvater(liveList[i].CoverImg, 'https://static.711688.net.cn/upload/adv/');
              liveList[i].ShareImg = utils.formatAvater(liveList[i].ShareImg, 'https://static.711688.net.cn/upload/adv/');
              if (liveList[i].CheckStatus == 1) {//审核通过的直播
                if (liveList[i].LiveStatus == 101) {
                  liveList[i].status = '直播中';
                  showList.push(liveList[i]);
                }
                else if (liveList[i].LiveStatus == 102) {
                  liveList[i].status = '未开始';
                  showList.push(liveList[i]);
                }
                else if (liveList[i].LiveStatus == 103) {
                  liveList[i].status = '已结束';
                  showList.push(liveList[i]);
                }
                else if (liveList[i].LiveStatus == 104) {
                  liveList[i].status = '禁播'
                }
                else if (liveList[i].LiveStatus == 105) {
                  liveList[i].status = '暂停中';
                  showList.push(liveList[i]);
                }
                else if (liveList[i].LiveStatus == 106) {
                  liveList[i].status = '异常';
                  showList.push(liveList[i]);
                }
                else {
                  liveList[i].status = '已过期'
                }
              }
            }
          }
          that.setData({
            liveList: showList
          })
        }
      },
    })
  },
  toLookLive: function (e) {
    let roomid = e.currentTarget.dataset.roomid;
    let cardId = wx.getStorageSync('cardId');
    wx.navigateTo({
      url: 'plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=' + roomid + '&custom_params=' + encodeURIComponent(JSON.stringify({
        cardId: cardId,
        saleUid: 0
      })),
    })
  },
  toLiveListByUser: function () {
    wx.navigateTo({
      url: '/live/myLiveList/index?type=1',
    })
  },

  //编辑首页腾讯视频
  editorMyVideo: function (e) {
    let id = e.currentTarget.dataset.id;
    let videoObj = this.data.videoObj;
    if (id == 1) {
      videoObj.show = false;
    } else {
      videoObj.show = true;
    }
    this.setData({
      videoObj: videoObj
    })
  },
  handleInputVideo: function (e) {
    this.setData({
      videosrc: e.detail.value
    })
  },
  updateMyVid: function () {
    let that = this;
    let videoObj = that.data.videoObj;
    let cardId = wx.getStorageSync('cardId');
    wx.request({
      url: app.globalData.host + '/api/staff/UpdateVid?staffid=' + cardId + '&videosrc=' + encodeURIComponent(that.data.videosrc),
      success: function (res) {
        if (res.data.Code == 0) {
          videoObj.show = true;
          that.data.videosrc = '';
          that.setData({
            videoObj: videoObj
          })
          utils.showToast('提交成功');
          that.getInfo(cardId);
        } else {
          utils.showModal(res.data.Message);
        }
      },
    })
  },

  //根据底部导航设置头部文字
  tabbareventListener: function (e) {
    let title = utils.getNavBarTitle(e, "/pages/index/index");
    this.setData({
      navTitleText: title
    })
  },

  // 绑定关系
  bindClient: function () {
    let that = this;
    let cardId = wx.getStorageSync('cardId');
    console.log('holderid',that.data.holderid)
    if (cardId && app.globalData.userInfo) {
      wx.request({
        url: app.globalData.host + '/api/BusinessCard/BindClient?staffId=' + cardId + '&uid=' + app.globalData.userInfo.Uid + '&source=' + that.data.source + '&shareUid=' + that.data.holderid,
        success: function (res) {
          console.log("进入名片页建立关系成功", cardId);
        },
      })
    } else {
      setTimeout(function () {
        that.bindClient();
      }, 1000)
    }
  },

  // 选择多张名片头图（商家版）
  chooseImageAvatar2: function () {
    var cardId = wx.getStorageSync("cardId")
    wx.navigateTo({
      url: '/pages/weijieke/myPhoto/index?staffid=' + cardId + '&location=0',
    })
  },

  //删除我的照片
  deletMyPhoto: function (e) {
    var that = this;
    var cardId = wx.getStorageSync("cardId");
    wx.showModal({
      title: '提示',
      content: '确定要删除此照片吗？',
      success(res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.host + '/api/Staff/DeleteStaffImgByIndex',
            data: {
              staffId: cardId,
              index: e.currentTarget.dataset.id
            },
            method: 'POST',
            success: function (res) {
              if (res.data.Code == 0) {
                that.getInfo(cardId);
              } else {
                utils.showModal(res.data.Message);
              }
            },
          })
        }
      }
    })
  },
  //领玖玖卡
  receiveJJK: function (saleUid) {
    let that = this;
    console.log('领玖玖卡',saleUid)
    if (app.globalData.userInfo) {
      let jjCard = app.globalData.jjCard;
      wx.request({
        url: app.globalData.host + '/api/Coupon/ReceiveCard?code=0&cardItemId='+ jjCard.Id +'&uid=' + app.globalData.userInfo.Uid + '&saleUid=' + saleUid,
        success: function (res) {                 
        }
      })
    } else {
      setTimeout(function () {
        that.receiveJJK(saleUid);
      }, 1000)
    }
  },
  
  getJJKInfo: function (callback) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Coupon/GetCardExists?uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0 && res.data.Data) {
          let item =res.data.Data
          that.setData({
            cardUser: {cid: item.Cid,saleUid: item.SaleUid,mobile: item.Phone}
          })
        }    
      }
    })
  }
})